﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LCA.Community.DAL.Interfaces;
using LCA.Community.DAL.Model;
using Microsoft.Practices.Unity;

namespace LCA.Community.Web.Models
{
    public class AvatarManager
    {
        public AvatarManager()
        {
        }

        public String GetUserAvatarUrl(String userName, HttpRequestBase request, UrlHelper urlHelper)
        {
            if (HasAvatar(request))
            {
                String fileName = request.Files.GetKey(0);
                var file = request.Files[fileName];
                if (file.ContentType.Substring(0, 5).Equals("image") || request.Cookies["thumbnail"] != null)
                {
                    return AvatarsRepository.GetUrl(userName,UserAvatar.UsersContainer).ToString();
                }            
            }

            return urlHelper.Content("~/Content/images/user.jpg");
        }

        public String GetGroupAvatarUrl(String groupName, HttpRequestBase request, UrlHelper urlHelper)
        {
            if (HasAvatar(request))
            {
                String fileName = request.Files.GetKey(0);
                var file = request.Files[fileName];
                if (file.ContentType.Substring(0, 5).Equals("image") || request.Cookies["thumbnail"] != null)
                {
                    return AvatarsRepository.GetUrl(groupName, GroupAvatar.GroupsContainer).ToString();
                }
            }

            return urlHelper.Content("~/Content/images/user.jpg");
        }

        public bool HasAvatar(HttpRequestBase request)
        {
            return request.Files.Count == 1 && request.Files[0].ContentLength != 0;
        }

        public void SaveUserAvatar(String userName, HttpRequestBase request)
        {
            String fileName = request.Files.GetKey(0);
            var file = request.Files[fileName];

            if (file.ContentLength != 0)
            {
                var avatar = new UserAvatar(userName, null, file.ContentType, file.InputStream);
                AvatarsRepository.Add(avatar);
            }
        }

        public void SaveGroupAvatar(string groupName, HttpRequestBase request)
        {
            String fileName = request.Files.GetKey(0);
            var file = request.Files[fileName];

            if (file.ContentLength != 0)
            {
                var avatar = new GroupAvatar(groupName, null, file.ContentType, file.InputStream);
                AvatarsRepository.Add(avatar);
            }
        }

        [Dependency]
        public IAvatarsRepository AvatarsRepository { get; set; }
    }
}